﻿using Microsoft.EntityFrameworkCore;
using QMERP.SeedWork;

namespace QMERP.Infrastructure.EFCore.Extensions
{
    public static class BaseEntityExtension
    {
        /// <summary>
        /// 根据Id获取实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static T? FindById<T>(this IQueryable<T> query, long id) where T : Entity<long>
        {
            return query.FirstOrDefault(x => x.Id == id);
        }
        /// <summary>
        /// 根据Id获取实体(异步)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static async Task<T?> FindByIdAsync<T>(this IQueryable<T> query, long id) where T : Entity<long>
        {
            return await query.FirstOrDefaultAsync(x => x.Id == id);
        }
        /// <summary>
        /// 获取全部忽视isEnable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <returns></returns>
        public static IQueryable<T> GetAll<T>(this IQueryable<T> query) where T : Entity<long>
        {
            return query.IgnoreQueryFilters();
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static IQueryable<T> Paging<T>(this IQueryable<T> query, int pageIndex, int pageSize)
        {
            return query.Skip(pageSize * (pageIndex - 1)).Take(pageSize);
        }
        /// <summary>
        /// 根据ids删除(假删除)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="ids"></param>
        public static async Task RemoveAsync<T>(this IQueryable<T> query, params long[] ids) where T : FullEntity<long>
        {
            List<T> entitys = await query.Where(x => ids.Contains(x.Id)).ToListAsync();
            foreach (T entity in entitys)
            {
                entity.IsEnable = false;
            }
        }
    }
}
